<?php


namespace app\controller;

use app\api\controller\Base;
use think\Db;
use think\Validate;

class Sd extends Base
{
    public function add_word()
    {
        $openid = input('openid');
        $content = input('content');

        $rule = [
            'open_id' => 'require|length:1,50',
            'content' => 'require|length:1,200',
        ];

        $msg = [
            'open_id.require' => 'openid错误',
            'open_id.length' => 'openid错误.',
            'content.require' => '请输入祝福内容',
            'content.length' => '请输入祝福内容.'
        ];

        $check_data = ['open_id' => $openid, 'content' => $content];
        $validate = new Validate();
        $validate->message($msg);
        $result = $validate->check($check_data, $rule);
        if (!$result) {
            $this->returnMsg(1001, $validate->getError(), []);
        }

        $check_data['add_time'] = date("Y-m-d H:i:s", time());
        $sd_info = Db::name('df_sd_add')->insert($check_data);
        if (!$sd_info) {
            $this->returnMsg(1000, '发送失败');
        }
        $this->returnMsg(200, '发送成功');
    }

    /**
     * 添加点赞
     */
    public function add_like()
    {
        $openid = input('openid');
        $sd_id = input('sd_id');

        $rule = [
            'open_id' => 'require|length:1,50',
            'sd_id' => 'require|number',
        ];

        $msg = [
            'open_id.require' => 'openid错误',
            'open_id.length' => 'openid错误.',
            'sd_id.require' => '祝福编号有误',
            'sd_id.number' => '祝福编号有误！.'
        ];

        $check_data = ['open_id' => $openid, 'sd_id' => $sd_id];
        $validate = new Validate();
        $validate->message($msg);
        $result = $validate->check($check_data, $rule);
        if (!$result) {
            $this->returnMsg(1001, $validate->getError(), []);
        }

        $add_like_info = Db::name('df_sd_histroy')->where(['sd_id' => $sd_id, 'open_id' => $openid])->find();
        if ($add_like_info) {
            $this->returnMsg(1002, '您已经给他点过赞了');
        }

        //修改点赞数量
        Db::name('df_sd_add')->where(['id' => $sd_id])->inc('likes', 1)->update();
        Db::name('df_sd_histroy')->insert(['sd_id' => $sd_id, 'add_time' => date("Y-m-d H:i:s", time()), 'open_id' => $openid]);
        $this->returnMsg(200, '点赞成功！');
    }

    /**
     * 获得点赞详情
     */
    public function get_card_msg()
    {
        $openid = input('openid');
        $sd_id = input('sd_id');

        $add_like_info = Db::name('df_sd_histroy')->where(['sd_id' => $sd_id, 'open_id' => $openid])->find();
        $card_info = Db::name('df_sd_add')->where(['id' => $sd_id])->find();

        $this->returnMsg(200, '点赞成功！', ['card_info' => $card_info, 'is_like' => $add_like_info ? 1 : 0]);
    }

    /**
     * 获得点赞前10排行
     */
    public function get_card_rank()
    {
        $card_info = Db::name('df_sd_add')->order('likes', 'desc')->limit(10)->select();
        $this->returnMsg(200, '点赞成功！', $card_info);
    }
}
